package org.phalanx.servlet.webmessages;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.phalanx.messenging.PhalanxMapDataMessage;
import org.phalanx.server.PhalanxServer;
import org.phalanx.server.ServerCache.CacheManager;
import org.phalanx.server.game.PhalanxMapCacheWrapper;
import org.phalanx.server.user.PhalanxUser;
import org.phalanx.servlet.websession.ServletAuthenticatorManager;
import org.phalanx.servlet.websession.UserWebSession;

public class PhalanxMapLoaderContext implements WebMessageable {
	public static final String CONTEXT = "loadmap";
	private PhalanxServer pServer;
	
	public PhalanxMapLoaderContext(PhalanxServer pServer){
		this.pServer = pServer;
	}
	
	@Override
	public void onContextLoadable(String context, Cookie authCookie,
			HttpServletRequest req, HttpServletResponse resp) {
		if (context.equals(CONTEXT)){
			ServletAuthenticatorManager s = new ServletAuthenticatorManager(pServer);

			if (authCookie != null && s.authenticate(authCookie) != null){
				String mapName = req.getParameter("mapname");

				if (mapName != null && !mapName.isEmpty()){
					CacheManager cacheMgr = pServer.getCacheManager();

					PhalanxMapCacheWrapper pMapWrap = (PhalanxMapCacheWrapper)cacheMgr.getElement("PhalanxMapCache", mapName);
					
					if (pMapWrap != null && pMapWrap.getMap() != null){
						PhalanxMapDataMessage pMapMsg = new PhalanxMapDataMessage();
						pMapMsg.setPhalanxMapData(pMapWrap.getMap());
						
						PhalanxUser u = (PhalanxUser)cacheMgr.getElement("TokenSessionCache", authCookie.getValue());
						UserWebSession session = (UserWebSession)cacheMgr.getElement("UserWebFeedCache", u.getId());
						
						session.sendMessage(pMapMsg);
						
						resp.setContentType("text/plain");
						
						try {
							resp.getWriter().write(pMapMsg.generateMessageBody());
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} // pMapWrap != null
				} // if mapName != null
			} // if auth
		} // if context

	}

}
